package com.cll.netty.netty.inboundlerAndOutboundhandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MyClientHandler extends SimpleChannelInboundHandler<Long> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        System.out.println("服务器地址：" + ctx.channel().remoteAddress());
        System.out.println("收到服务器消息：" + msg);
    }

    /**
     * 分析
     * 1. "abcdabcdabcdabcd"是16个字节
     * 2. 该处理器的前一个handler是MyLongToByteEncoder
     * 3. MyLongToByteEncoder父类是MessageToByteEncoder
     * 4. MessageToByteEncoder父类是
     *
     * public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
     *         ByteBuf buf = null;
     *
     *         try {
     *             if (this.acceptOutboundMessage(msg)) { // 判断当前msg是不是应该处理的类型，如果是就处理，如果不是就跳过
     *                 I cast = msg;
     *                 buf = this.allocateBuffer(ctx, msg, this.preferDirect);
     *
     *                 try {
     *                     this.encode(ctx, cast, buf);
     *                 } finally {
     *                     ReferenceCountUtil.release(msg);
     *                 }
     *
     *                 if (buf.isReadable()) {
     *                     ctx.write(buf, promise);
     *                 } else {
     *                     buf.release();
     *                     ctx.write(Unpooled.EMPTY_BUFFER, promise);
     *                 }
     *
     *                 buf = null;
     *                 } else {
     *                 ctx.write(msg, promise);
     *             }
     *
     * 5. 因此我们编写Encoder 是要注意传入的数据类型和处理的数据类型一致
     * @param ctx
     * @throws Exception
     */
    // 重写chnnelAction发送数据
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler 发送数据");
        ctx.writeAndFlush(123456L); // 发送的是一个long
        //ctx.writeAndFlush(Unpooled.copiedBuffer("abcdabcdabcdabcd", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        System.out.println("出现异常");
    }
}
